<?php

namespace frontend\models\cyf;

use frontend\controllers\common;
use Yii;
use yii\db\ActiveRecord;
use yii\validators\RequiredValidator;


class User extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '2008a_user';
    }

    public function getMemberCard()
    {
        return $this->hasOne(MemberCard::class,['id'=>'membership']);
    }

    /**
     * 用户登录
     * @param $params
     * @return array|string
     * @throws \Exception
     * @name cyf
     */
    public static function login($params)
    {
        //根据手机号查询用户信息
        $user = self::find()->where(['phone'=>$params['phone']])->all();
        if($user){
            $user= $user[0]->toArray();
            return $user;
        }
        return false;
    }

    /**
     * 添加用户
     * @param $phone
     * @return bool|mixed|\yii\db\ActiveRecord
     * @name cyf
     */
    public static function createUser($phone)
    {
        $user = new User();
        $user->phone = $phone;
        if($user->save()) return true;
        return false;
    }

    /**
     * 根据手机号查用户
     * @param $phone
     * @name cyf
     */
    public static function getUserOneBYPhone($phone)
    {
        return self::find()->where(['phone'=>$phone])->all()[0];
    }

    /**
     * 更新密码
     * @param $params
     * @return bool
     * @name cyf
     */
    public static function createPassword($params)
    {
        $user =self::find()->where(['id'=>$params['uid']])->all()[0];
        if(!$user){
            return false;
        }
        $user->password = common::lock_url($params['password']);
        return $user->save();
    }

    /**
     * 查询用户信息
     * @param $id
     * @return mixed|ActiveRecord
     * @nane cyf
     */
    public static function getOneUserById($id)
    {
        return self::find()->joinWith('memberCard')
            ->select('*')
            ->where(['2008a_user.id'=>$id])
            ->asArray()->all()[0];
    }

    /**用户降级
     * @param $id
     * @return bool
     * @name cyf
     */
    public static function downGrad($id)
    {
        $user = self::find()->where([''=>$id])->all()[0];
        $user->registration_time = date('Y-m-d H:i:s');
        $user->membership = $user->membership-1;
        $user->member = 0;
        return $user->save();
    }

    /**
     * 用户加积分
     * @param $arr
     * @return bool
     * @name cyf
     */
    public static function upScore($arr)
    {
      $user = self::find()->where(['id'=>$arr['uid']])->all()[0];
      $user->member = $user->member + $arr['integral'];
      return $user->save();
    }

    public static function upGrade($id,$fen=2000)
    {
        $user = self::find()->where(['id'=>$id])->all()[0];
        $user->membership = $user->membership+1;
        $user->member = $user->member -$fen;
        return $user->save();
    }
}
